package com.faner4cloud.yun.queue.delay;

import com.faner4cloud.yun.queue.delay.handler.DelayTypeHandlerFactory;
import com.faner4cloud.yun.queue.delay.handler.DelayTypeHandlerStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 延迟队列任务监听
 *
 * @author faner
 * @since 2022-04-14
 */
@Component
@Slf4j
public class TaskRemindServiceImpl {


	@Autowired
	private RedisDelayQueueManager redisDelayQueueManager;
	@Autowired
	private DelayTypeHandlerFactory delayTypeHandlerFactory;

	/**
	 * 监控过期的KEY在延迟队列中
	 */
	@PostConstruct
	public void monitorExpiredKeyInDelayQueue() {
		log.info("#TaskRemindServiceImpl#延迟队列监听任务开始执行");
		//订单自动取消延迟队列
		new Thread(() -> {
			this.processDelayType(DelayTypeEnum.ORDER_PAY_AUTO_CANCEL_DELAY);
		}, "ORDER_PAY_AUTO_CANCEL_DELAY").start();

	}

	private void processDelayType(DelayTypeEnum delayTypeEnum) {
		while (true) {
			//阻塞型获取
			String delayTypeValue = redisDelayQueueManager.popup(delayTypeEnum);
			log.info("#TaskRemindServiceImpl#延迟队列监听任务拉取到值：{}", delayTypeValue);
			if (delayTypeValue == null) {
				return;
			}
			//获取下对应延迟的处理类
			DelayTypeHandlerStrategy handler = this.delayTypeHandlerFactory.getDelayTypeHandlerStrategy(delayTypeEnum.getCode());
			if (null == handler) {
				return;
			}
			//处理
			handler.execute(delayTypeValue);
		}
	}
}
